package com.zachary.zbigdata.brank.spark.yarn;


import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zachary
 * Date: 14-5-2
 * Time: 下午3:43
 * PC：ubuntu'IDEA in home
 */
public class WordCount {


    public static void main(String[] args) throws Exception {
        /**
         * have to set path SPARK_JAR and SPARK_YARN_APP_JAR
         * spark提交任務到yarn請參考:http://my.oschina.net/132722/blog/220096
         */
        SparkConf sparkConf = new SparkConf();
        sparkConf.setAppName("wordcount");
        sparkConf.setMaster("yarn-client");

        JavaSparkContext ctx = new JavaSparkContext(sparkConf);


        JavaRDD<String> lines = ctx.textFile("hdfs://zachary-pc:9000/user/hadoop/nie.txt", 1);

        JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            public Iterable<String> call(String s) {
                return Arrays.asList(s.split(" "));
            }
        });

        JavaPairRDD<String, Integer> ones = words.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String s) {
                return new Tuple2<String, Integer>(s, 1);
            }
        });


        JavaPairRDD<String, Integer> counts = ones.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer i1, Integer i2) {
                return i1 + i2;
            }
        });

        List<Tuple2<String, Integer>> output = counts.collect();
        System.out.println("counts:" + output.size());
        for (Tuple2 tuple : output) {
            System.out.println(tuple._1 + ": " + tuple._2);
        }

        System.exit(0);

    }
}